import json

import requests
from django.conf import settings


class ShareWB():
    """微博分享类"""

    # https://api.weibo.com/oauth2/authorize
    def getWB_code (self):
        # 获取微博授权页
        send_rul = """https://api.weibo.com/oauth2/authorize?""" \
                   + "client_id=" + settings.WBCONFIG.get("client_id", None) + "&redirect_uri=" + settings.WBCONFIG.get(
            "redirect_uri", None)
        return send_rul

    # https://api.weibo.com/oauth2/access_token  获取token的地址
    def getWB_token (self, code):
        """获取access_token"""
        url = 'https://api.weibo.com/oauth2/access_token'
        data = {'client_id': settings.WBCONFIG.get("client_id", None),
                'client_secret': settings.WBCONFIG.get("app_Secret", None),
                "grant_type": "authorization_code", "code": code,
                "redirect_uri": settings.WBCONFIG.get("redirect_uri", None)}
        return_data = requests.post(url, data=data).content.decode("utf-8")  # 获取返数据，用于第二步
        return_data = json.loads(return_data)
        access_token = return_data.get("access_token")
        return access_token

    # https://api.weibo.com/2/statuses/share.json 分享地址
    def sharetsukkomi (self, access_token, status):
        """获取分享成功的返回信息"""
        url = "https://api.weibo.com/2/statuses/share.json"
        status = str(status) + "http://www.mmp.com"
        data = {"access_token": str(access_token), "status": status}
        return_data = requests.post(url, data=data).content.decode("utf-8")  # 分享成功的返回信息
        return_data = json.loads(return_data)
        wbidstr = return_data.get("idstr")
        return wbidstr
